<?php

namespace app\api\controller;

use app\common\model\Discuss as D;
use think\facade\Db;

class Discuss extends ApiBase {
	// 不需要验证token的方法
	protected $middleware = [
		'app\api\middleware\Auth' => ['except' => ["list", "detail"]],
	];

	//话题列表
	public function list() {
		$topicId = input("topic_id");
		$active = input("order");
		$topType = input("top_type");

		$where = [];
		if ($topicId) {
			$where["topic_id"] = $topicId;
		}

		$order = "id desc";
		if ($active == 'hot') {
			$order = "read_count desc";
		}

		if ($topType) {
			$where[] = ["top_type","=",$topType];
		}

		$list = D::getList($where, $order);
		return success($list);
	}
	//添加话题
	public function addDis() {
		$data = input("post.");
		$uid = $this->uid;
		$data["uid"] = $uid;
		$data["create_time"] = time();
		if ($this->checkText($data["title"]) != 0) {
			return error("内容违规违法");
		}
		$res = D::create($data);
		if ($res) {
			return notice("话题创建成功");
		}
		return error("话题创建失败");
	}
	//修改话题
	public function editDis() {
		$data = input("post.");
		$uid = $this->uid;
		$data["uid"] = $uid;
		if ($this->checkText($data["title"]) != 0) {
			return error("内容违规违法");
		}
		$res = D::update($data);
		if ($res) {
			return notice("修改成功");
		}
		return error("修改失败");
	}
	public function detail() {
		$id = input("id");
		Db::name('discuss')->where('id', $id)->inc('read_count')->update();
		$res = D::withJoin(["userInfo" => ["username", "avatar"]])->where("id", $id)->find();
		$res["post_count"] = D::name("post")->where("discuss_id", $id)->count();
		return success($res);
	}

	//我创建的话题
	public function myDis() {

		$uid = $this->uid;
		$where["discuss.uid"] = $uid;
		$list = D::getList($where);
		return success($list);
	}
	//删除话题
	public function del() {
		$id = input("id");
		$res = D::destroy($id);
		if ($res) {
			return notice("删除成功");
		}
		return error("删除失败");
	}
	//删除选择的话题
	public function Changedel() {
		$id = input("id");
		$ids = explode($id, ",");
		$res = D::destroy($ids);
		if ($res) {
			return notice("删除成功");
		}
		return error("删除失败");
	}
}